<?php

declare(strict_types=1);

namespace sheep\middleware;

use sheep\facade\Auth;
use sheep\exception\SheepException;

class CheckRule
{
    public function handle($request, \Closure $next, $guard = 'admin')
    {
        // 暂只支持后台
        $auth = Auth::guard($guard);

        if (!$auth->isSuper()) {
            $root = substr($request->root(), 1);
            $controller = $request->controller();
            $action = $request->action();
            $access = strtolower("{$root}.{$controller}.{$action}");
            $userAccess = $auth->getAccess(false); // 为了调试方便 先把缓存关闭
            if (!in_array($access, $userAccess['permission'])) {
                throw (new SheepException)->accessError();
            }
        }

        return $next($request);
    }
}
